using Microsoft.Extensions.Logging;
using System.Text.Json;
using SumerCoreDevOps.Domain.Entities;
using SumerCoreDevOps.Infrastructure.Data;
using SumerCoreDevOps.Shared.Enums;

namespace SumerCoreDevOps.Infrastructure.Workflow;

/// <summary>
/// 工作流定义管理器
/// </summary>
public class WorkflowDefinitionManager
{
    private readonly FreeSQLProvider _dbProvider;
    private readonly ILogger<WorkflowDefinitionManager> _logger;

    public WorkflowDefinitionManager(FreeSQLProvider dbProvider, ILogger<WorkflowDefinitionManager> logger)
    {
        _dbProvider = dbProvider;
        _logger = logger;
    }

    /// <summary>
    /// 创建工作流定义
    /// </summary>
    public async Task<WorkflowDefinition> CreateWorkflowAsync(
        string name,
        string? description,
        string version,
        string? createdBy)
    {
        var workflow = new WorkflowDefinition
        {
            Name = name,
            Description = description,
            Version = version,
            CreatedBy = createdBy,
            IsEnabled = true
        };

        workflow.Id = (long)await _dbProvider.Orm.Insert(workflow).ExecuteIdentityAsync();

        _logger.LogInformation("创建工作流定义: {Name}, ID: {Id}", name, workflow.Id);
        return workflow;
    }

    /// <summary>
    /// 添加阶段
    /// </summary>
    public async Task<Stage> AddStageAsync(
        long workflowId,
        string name,
        int order,
        ExecutionMode executionMode,
        string? triggerCondition = null)
    {
        var stage = new Stage
        {
            WorkflowDefinitionId = workflowId,
            Name = name,
            Order = order,
            ExecutionMode = executionMode,
            TriggerCondition = triggerCondition
        };

        stage.Id = (long)await _dbProvider.Orm.Insert(stage).ExecuteIdentityAsync();

        _logger.LogInformation("添加阶段: {Name} 到工作流 {WorkflowId}", name, workflowId);
        return stage;
    }

    /// <summary>
    /// 添加步骤
    /// </summary>
    public async Task<Step> AddStepAsync(
        long stageId,
        string name,
        StepType stepType,
        int order,
        string stepConfig,
        string? command = null,
        int timeoutSeconds = 300,
        int maxRetries = 0,
        int retryIntervalSeconds = 10)
    {
        var step = new Step
        {
            StageId = stageId,
            Name = name,
            StepType = stepType,
            Order = order,
            StepConfig = stepConfig,
            Command = command,
            TimeoutSeconds = timeoutSeconds,
            MaxRetries = maxRetries,
            RetryIntervalSeconds = retryIntervalSeconds
        };

        step.Id = (long)await _dbProvider.Orm.Insert(step).ExecuteIdentityAsync();

        _logger.LogInformation("添加步骤: {Name} 到阶段 {StageId}", name, stageId);
        return step;
    }

    /// <summary>
    /// 获取工作流定义（含阶段和步骤）
    /// </summary>
    public async Task<WorkflowDefinition?> GetWorkflowWithDetailsAsync(long workflowId)
    {
        var workflow = await _dbProvider.Orm.Select<WorkflowDefinition>()
            .Where(w => w.Id == workflowId)
            .IncludeMany(w => w.Stages, then => then.IncludeMany(s => s.Steps))
            .FirstAsync();

        if (workflow != null)
        {
            // 排序阶段和步骤
            workflow.Stages = workflow.Stages.OrderBy(s => s.Order).ToList();
            foreach (var stage in workflow.Stages)
            {
                stage.Steps = stage.Steps.OrderBy(s => s.Order).ToList();
            }
        }

        return workflow;
    }

    /// <summary>
    /// 获取所有启用的工作流
    /// </summary>
    public async Task<List<WorkflowDefinition>> GetEnabledWorkflowsAsync()
    {
        return await _dbProvider.Orm.Select<WorkflowDefinition>()
            .Where(w => w.IsEnabled)
            .ToListAsync();
    }

    /// <summary>
    /// 禁用工作流
    /// </summary>
    public async Task DisableWorkflowAsync(long workflowId)
    {
        await _dbProvider.Orm.Update<WorkflowDefinition>()
            .Set(w => w.IsEnabled, false)
            .Set(w => w.UpdatedAt, DateTime.UtcNow)
            .Where(w => w.Id == workflowId)
            .ExecuteAffrowsAsync();

        _logger.LogInformation("禁用工作流: {WorkflowId}", workflowId);
    }

    /// <summary>
    /// 启用工作流
    /// </summary>
    public async Task EnableWorkflowAsync(long workflowId)
    {
        await _dbProvider.Orm.Update<WorkflowDefinition>()
            .Set(w => w.IsEnabled, true)
            .Set(w => w.UpdatedAt, DateTime.UtcNow)
            .Where(w => w.Id == workflowId)
            .ExecuteAffrowsAsync();

        _logger.LogInformation("启用工作流: {WorkflowId}", workflowId);
    }

    /// <summary>
    /// 删除工作流定义
    /// </summary>
    public async Task DeleteWorkflowAsync(long workflowId)
    {
        try
        {
            var stages = await _dbProvider.Orm.Select<Stage>()
                .Where(s => s.WorkflowDefinitionId == workflowId)
                .ToListAsync();

            foreach (var stage in stages)
            {
                await _dbProvider.Orm.Delete<Step>()
                    .Where(s => s.StageId == stage.Id)
                    .ExecuteAffrowsAsync();
            }

            // 删除阶段
            await _dbProvider.Orm.Delete<Stage>()
                .Where(s => s.WorkflowDefinitionId == workflowId)
                .ExecuteAffrowsAsync();

            // 删除工作流
            await _dbProvider.Orm.Delete<WorkflowDefinition>()
                .Where(w => w.Id == workflowId)
                .ExecuteAffrowsAsync();

            _logger.LogInformation("删除工作流: {WorkflowId}", workflowId);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除工作流失败: {WorkflowId}", workflowId);
            throw;
        }
    }

    /// <summary>
    /// 验证工作流定义的完整性
    /// </summary>
    public async Task<(bool IsValid, List<string> Errors)> ValidateWorkflowAsync(long workflowId)
    {
        var errors = new List<string>();
        var workflow = await GetWorkflowWithDetailsAsync(workflowId);

        if (workflow == null)
        {
            errors.Add($"工作流 {workflowId} 不存在");
            return (false, errors);
        }

        if (workflow.Stages.Count == 0)
        {
            errors.Add("工作流至少需要一个阶段");
        }

        foreach (var stage in workflow.Stages)
        {
            if (stage.Steps.Count == 0)
            {
                errors.Add($"阶段 '{stage.Name}' 至少需要一个步骤");
            }

            // 验证触发条件格式
            if (!string.IsNullOrEmpty(stage.TriggerCondition))
            {
                try
                {
                    JsonDocument.Parse(stage.TriggerCondition);
                }
                catch
                {
                    errors.Add($"阶段 '{stage.Name}' 的触发条件格式不正确");
                }
            }
        }

        return (errors.Count == 0, errors);
    }
}
